# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import hashlib
import time
from importlib import reload
import logging
reload(sys)

YOUDAO_URL = 'https://openapi.youdao.com/v2/api'

APP_KEY = '418889b16fdd449c'
# 您的应用密钥
APP_SECRET = 'LbRzvX3oogSxlgOlmOlOKTCENEBRn8sC'



def convert_to_utf8(text):
    # 将文本转换为UTF-8编码的字节序列
    text_bytes = text.encode('utf-8')

    # 将字节序列解码为UTF-8编码的字符串
    text_utf8 = text_bytes.decode('utf-8')

    return text_utf8

def retry_on_translate(max_retries=3, delay=1):
    """
    失败重试装饰器：在函数执行失败时进行重试
    :param max_retries: 最大重试次数
    :param delay: 重试之间的延迟时间，默认为1秒
    """
    def decorator(func):
        def wrapper(*args, **kwargs):
            retries = 0
            while retries < max_retries:
                try:
                    result = func(*args, **kwargs)
                    new_text_list = [item["translation"] for item in result['translateResults']]
                    logging.info("translateResults: >> {}".format(new_text_list))
                    return result
                except Exception as e:
                    logging.info(f"Exception occurred: {e} translateResults: {result}, {(args, kwargs)}")
                    retries += 1
                    logging.info(f"Retrying ({retries}/{max_retries})...")
                    time.sleep(delay)
            logging.info(f"Max retries exceeded. Failed to execute {func.__name__}.")
        return wrapper
    return decorator

@retry_on_translate(max_retries=3, delay=1)
def batch_translate(qArray, lang_from, lang_to):
    '''
    韩语：ko
    英语：en
    简体中文：zh-CHS
    '''
    qArray = [convert_to_utf8(text) for text in qArray]
    data = {}
    data['from'] = lang_from
    data['to'] = lang_to
    data['signType'] = 'v3'
    curtime = str(int(time.time()))
    data['curtime'] = curtime
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(''.join(qArray)) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)
    data['appKey'] = APP_KEY
    data['q'] = qArray
    data['salt'] = salt
    data['sign'] = sign
    data['vocabId'] = "您的用户词表ID"
    response = do_request(data)
    return response.json()


def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()


def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)


if __name__ == '__main__':
    s = batch_translate(['他开发语言请参照 接口API文档 进行开发，也欢迎企业咨询来提出你们需要的'], 'zh-CHS', 'ko')
    print(s)